<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\response\Json;
use Yansongda\Pay\Pay;

/**
 * 提现管理
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{

    /**
     * Withdraw模型对象
     * @var \app\admin\model\Withdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Withdraw;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $rows = $list->items();
        $total = $list->total();
        foreach ($rows as &$v){
            $v->avatar = DB('user')->where('id',$v->user_id)->value('avatar');
            $v->user_id = DB('user')->where('id',$v->user_id)->value('nickname');
            $v->des = empty($v->des)?'':$v->des;
        }
        $result = ['total' => $total, 'rows' => $rows];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $status1 = $row->status;
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        if($status1 == 0 && $params['status']==1){
            \app\common\model\User::money(-$row->money,$row->user_id,'提现');
        }
        $this->success();
    }

    public function agree($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status = 1;
        $row->save();
        \app\common\model\User::money(-$row->money,$row->user_id,'提现');
        $this->success('操作成功');
    }

    public function bohui($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status = 2;
        $row->save();
//        \app\common\model\User::money(-$row->money,$row->user_id,'提现');
        $this->success('操作成功');
    }
    public function alipayAgree($ids)
    {
        /*  $info = $this->model->get($ids);
          $info->state = 2;
          $info->save();
          $this->success("审核成功");*/
        Db::startTrans();
        try {
            $info = Db::name("user_withdraw")->where(['id'=>$ids])->find();
            //$info = $this->model->get($ids);
            //var_dump($info);
            if($info['status'] != 0){
                   throw new Exception("重复操作");
            }
            //$user = User::get($info->user_id);
           // $bank = Db::table('fa_user_bank')->where('user_id',$info->user_id)->find();
            if (empty($info['alipay_name']) || empty($info['alipay_account'])) {
                throw new Exception("该用户支付宝信息未绑定或缺少信息");
            }
            //客首配置
            $config2 = [
                'app_id'              => '2021001146631427',
                'notify_url'          => '/addons/epay/api/notifyx/type/alipay',
                'ali_public_key'      => __DIR__ . '/ksalipay/alipayCertPublicKey_RSA2.crt',
                'private_key'         => 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC59flp7OEimUJ5mScXCINhQWgF61c0MZhF7u82dKUeY81rllIiS05PypEhNtZ2To3pDhW5NXekfukE5L0etHL9TmK2QDbDb+ugubK8p2ODgEljaaP7EDNHlisnobQJ7Ymam+YCnPRwPJ5GKs4bzgr9mG1hsRLUvrCDN7HRG/8dc1U4C6TN8IFbdPejjSuEHlgbzOXX4ccMRyjCWyiJmffVA2WDw7CjW7q5FnQfCxxnnvzEaYmc+PVFCDg76+7KIzOV8CwNiRxT6Wy2YhPPrRpfol/j8LGOP9DZ7PJahl8wuxom5UN1mPSHdY+rEn+ZKR8eyzOzPoX3n0FIVY6Wlt3RAgMBAAECggEBAJkMepPVY42IOY++ns90MDzxCd4lTQYl8z9LYRGeeu9CEKUFeN/EvtUo0L1XVrbT/DPdZb+i4688zCc84vHMbf9Qbim1O90p1fHYI+TklyB5iu0I2u8c7Dd0vlvF2Fl7aI8Y0/s+lmdxXIo/XJbBw4Xn185ZYDg8ISY9xllmA1eGV2lhqUYv86JRYUfOiS86jSsT1TYM/CleWpvIxB8m8N271yAV7xoEGn+usRB7LGf0OgNtyEVzCOxSb9Rw88sW75JdW8mXeVf1CSDptLRExtUe0QkctGKGpRuDo74RXK4D3uAJQ8JPB6vYWLO8x8Bhx4ToT588isAT7ZVRf9nJWuECgYEA3ADWp8uGPliMM7Zc8AsOCc9yk23SE9nROhrHZ4k8DzsmUi+0N/eh9w5MUekDzm9t3Yuak9FigAIMJlI4TiaqiHNCTsoLlgO59+IspTULt5NOEMlT6G+FvmFnDFXkGlG195ajAQAfggIrorJ+46jEEuEYJDuXf9fH8nBygGZ+kK0CgYEA2GM30swreHPCY7mgbXOPMrcUlH3GrJHbTS3XIZsT/cjp+Li423VPQeNqXIlBsB/2QoaUmjdnzR3fWtRGDktZooAvJlm3Kt3ICo1wZokek2FyYU+IoE5zG94UFqFFmdJJxSsd6gyDbvT1ARW/x5RZbfsVLj5sDqyP9wEgTeAp0jUCgYEAn2McIMSapWCRcoWUH3Ri30ijwZu2rxsHMglkneYW1RINWU2mS0Xk2ZBKSq1+THj+J5uUibMQoZzaIIlAsZ3hvqmCSIKoki5w9N2vaqFbs8vMquyxFZx2UM9QUOeJMmgwZQeFYJwuN4pLArw+ocELDIJ3cwiZYc161nIRAmU/HKECgYBWMh+4jq/6SVJz2yu2rcOrFhbSl8+eSnOrKMl7j4TFIVViSGMKuI4b1vU1a0+JUxILqgRj8hIdOPsR+WD2rLlF6/3cLvyxzKq02Wae0ZwmZTjk3oO0J8vem/YwlYleHtBYBDbkVpu8hUNbbUh5vfRpxQzI4QC2T7MBV6eAnfzKyQKBgGBtyQjlhFWh+SjDIPwcX6hLiUBrsioYQQWCrwFK00zluDaiQsJYHIvwdW8sFbuHj/XKkoM09vrUeKtepcA+JfEECQoNtLSYxc+8e+cXxfJWZXaa/OH3/bv9PQqxev8XJqxtFIH4tVaB6QQQsxHS1fG/3DQyLHgHZpIzyOknBKqB',
                'app_cert_public_key' => __DIR__ . '/ksalipay/appCertPublicKey_2021001146631427.crt', //应用公钥证书路径
                'alipay_root_cert'    => __DIR__ . '/ksalipay/alipayRootCert.crt', //支付宝根证书路径

                'log' => [ // optional
                    'file' => './logs/alipay.log',
                    'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
                    'type' => 'single', // optional, 可选 daily.
                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                ],
                'http' => [ // optional
                    'timeout' => 5.0,
                    'connect_timeout' => 5.0,
                    // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
                ],
//                 'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
            ];
            //河南小春云配置
            $config3 = [
                'app_id'              => '2021003175600645',
                'notify_url'          => '/addons/epay/api/notifyx/type/alipay',
                'ali_public_key'      => __DIR__ . '/alipay/alipayCertPublicKey_RSA2.crt',
                'private_key'         => 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCVFlesfj2S8TsB5BaP2QoiBvayP05Rai3N+F/PyNvbb0RDJkW5M8oAbVKxLHSdwe4SktcwkX1/dBvGyxI3AB5knwmUARCo3U+uzkCKVgfEqrWjmZHl/0S+Mp1KSj4fuzYqrwokh9NHP6UHzhQd5jiL8XbK9NYVMTrsNALYLUlYK2bPKPT95YW0EEJzQutwF7C1qjADom8WNVIIKfGzFaApza99qfzT6hDPEI94Q5OyIB37FTsTr3vDGJXYl7Pf+xwLGL4yfjk+qcRqQOg3ZntbITsaCPPFBMlscoHvNTmiqKOkXrrxJPc7Xi+Y2FlfEYDw+oLI9CoP9GSX67EXRG8rAgMBAAECggEBAIAygB1hSE0shZLwsL3s4Zu05TkM2qmDZfOw2aJwky0zlj0vkdDZSZ/oYazcD0MAWVk7TzMCSCnqi1/7iqQkw/2+C5xq9gpek4A69qB9rZxdNmeBTEW7pT7vgvU4tgbPEprNfSlAalrfzWbSu9Wh+4nKjl2i/tumQ4aMis2c026uQQInUK4zDOh5ncep/+yIW7RuVrx2TLWIhxeYw274OtNdV5ViAvSDhp0f/fblpuUsKfFxV4PWjY79sR4mDK9kjIPfQNXclR6dhsHmIsWwYeNseaP/d16b5euM00cUmgu6NoPo0UzOZD0AMBoTdszuV9CTGINBf9Do50/zOIxxPuECgYEA3GYD2e4zK7Y2WzRT6/CIOLNog8a67cOqRBAXswAkOaqqmy5r+/QACKprXjlbkIviBr6thVsufKf1tHncliyANHLuUcG6pO+coAi8zczrB96EaQ4Gmzpeb1pZyuO5CoqKTLlf4ySNJf0N0oPfWUEVNUgr/k64uZ1rk+AT72wgzjkCgYEArStxwXHkpwnE1UKM8zQKhUwVoWU2LfuLbJosj4rVFQCRNWLjAJTgH6KVrbiZJIaGai23nJ8VIxhupKl2Wo7L8B+qso6FedsOBrg5J4uQ7AF8Oesdagova9XPtbpX/dmHITRRYOi2vUkWWSDpslXDzIqDAz6rB9hVVhaZ8jRSKIMCgYEAyJuCfea2ZN8hcrqaeHMjSpjiVK+ajbg/TlxndeJ3FpYlW8JRP6/EKB8WQ1lp4pOwU/tS7cMk+QnYN0GEapxuxU6nZXs0a9Q9d9z8HUab1znOw+CkWr4yHqDagjXsw49+en9wq8slPqKq5iZqMU9wAmOCx6LXuPt0Y9Dd1FtTMOECgYBJh80Byw7ALtG5jEy1aD+fYjM9GPDsjYciUkThnp3kER2XganKMW0Jgcv0vBGrBMRGiasRgitDf7hbiumKgl/uUkP1FbdviqhmCgua0xRyYh8RqNgQksqYC23rSHjcfWV3n/N+JtKRhVtL9UHGS8ycKaR/2DhfWGjD6UztH3JTaQKBgQCga7MbedYD2lhgwvEiB7+Vo0UIOvgoFYm+1aWNjDFY2NGVMaqdIkkuzVBiFPsCF0bSG5wpxO7jlLYrbarTwUhTZnPgh2qeWhgHSvGL532B00/LkBPbvoR250E7MasBZZO717eMAQKa13QWmIeVaSwScBPI5H6ohm7Sn5opRFKl3Q==',
                'app_cert_public_key' => __DIR__ . '/alipay/appCertPublicKey_2021003175600645.crt', //应用公钥证书路径
                'alipay_root_cert'    => __DIR__ . '/alipay/alipayRootCert.crt', //支付宝根证书路径

                'log' => [ // optional
                    'file' => './logs/alipay.log',
                    'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
                    'type' => 'single', // optional, 可选 daily.
                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                ],
                'http' => [ // optional
                    'timeout' => 5.0,
                    'connect_timeout' => 5.0,
                    // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
                ],
                //'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
            ];
            //深圳小春云配置
            $config = [
                'app_id'              => '2021004130644393',
                'notify_url'          => '/addons/epay/api/notifyx/type/alipay',
                'ali_public_key'      =>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cScdZhTyn/Ox0qAGR14RAcLsl46a1zaf4uILHfhBq3Nh2xSgLFae7DDf8X2Bhv9qdopU5bXgw6DwKBgGGF3GJHtDV3OUShtbqs6HuASsMwZK41lOk8g2PLpXmZy4tx1lHR+pZU/iwgeRn6aT4Dn6KaoAJ9jh5730cocKHGbVmNaVrTExrgxC+VLgkkzdDe5EO6RMjPopqMy6jY7TPQcel4sh5BibVFiYYM/gcUoFfo8iq7QT5Q6pywcGNjAoGAXzZFkr5pdcBIWY+nxUQhKk/AwIdqU/KeMH+DjmmHXt1IbnKvU9iznlZKFt0JuDOgtcaDmcdRUOaQKuZ7kQr1Ukg5wEfkDqGaXc0KyWh4rce4wwQo8o6h0fD40+fX6RCN1KWOm41IMM9rgGBYivjdBvPrbCGFsAwbeVhvhm4UFecCgYBemDzVsx5AeRXmjfAn9M80QP5bQKixJmBP9Kt5tuyXXPoT3qnr70bM6qxuRjfv4/exRwvQF5ZwGJuE3BtVZZOjjvPPelp71bwcB6hCeEsywWrtN+anciYyokpkJngBClllGgYKwnHz9jWczh83ryO6y5L8xwDqp4OjPwe1v5GKaA==',
                'app_cert_public_key' => __DIR__ . '/szalipay/appCertPublicKey_2021004130644393.crt', //应用公钥证书路径
                'alipay_root_cert'    => __DIR__ . '/szalipay/alipayRootCert.crt', //支付宝根证书路径

                'log' => [ // optional
                    'file' => './logs/alipay.log',
                    'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
                    'type' => 'single', // optional, 可选 daily.
                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                ],
                'http' => [ // optional
                    'timeout' => 5.0,
                    'connect_timeout' => 5.0,
                    // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
                ],
                //'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
            ];
            $order = [
                'out_biz_no' => time(),
                'trans_amount' => $info['true_money'],
                'product_code' => 'TRANS_ACCOUNT_NO_PWD',
                'payee_info' => [
                    'identity' => $info['alipay_account'],
                    'identity_type' => 'ALIPAY_LOGON_ID',
                    'name' => $info['alipay_name']
                ],
                'biz_scene' => "DIRECT_TRANSFER"
            ];
            $alipay = Pay::alipay($config3);
            $result = $alipay->transfer($order);
            Log::info('aaaaaaaa'.json_encode($result));
            if ($result->code == '10000') {
               // $info->state = 1;
                //$info->save();
                Db::name("user_withdraw")->where(['id'=>$ids])->update(['status'=>1]);
                Db::commit();
                $this->success("审核成功");
            }
            throw new Exception("操作失败，请检查日志");

        } catch (Exception $exception) {
            Db::rollback();
            //var_dump($exception->getMessage());
            if (strstr($exception->getMessage(), "PAYEE_NOT_EXIST")) {
                $this->error("收款账号不存在或户名有误，建议核实账号和户名是否准确");
            }
            $this->error("操作失败：" . $exception->getMessage());
        }
    }
}
